<template>
  <div class="add-card">
    <div>
       <header class="header">
         <el-page-header @back="$router.back()" 
         :content="$route.params.id ? '编辑月卡' : '添加月卡'"
         style="margin-left: 20px;">
    <template #content >
      <!-- <span class="text-large font-500 mr-3" > 添加月卡 </span> -->
    </template>
  </el-page-header>
  <div style=" margin-right: 40px; ">管理员</div>
    </header>
    <main >
        <div class="card-main">
          <text>车辆信息</text>
           <el-divider />
          <div>
            <el-form  ref="carInfoFormRef" :rules="carInfoRules" :model="carInfoForm" style="display: flex; flex-wrap: wrap;padding-right: 50px;
            margin-left: 130px; justify-content: space-between; 
            width: 90%;
            ">
              <el-form-item label="车主姓名：" prop="personName">
                <el-input placeholder="请输入车主姓名"  v-model="carInfoForm.personName" style="  width: 480px;" ></el-input>
              </el-form-item>
              <el-form-item label="联系方式：" prop="phoneNumber">
                <el-input placeholder="请输入联系方式" v-model="carInfoForm.phoneNumber" style="width: 480px;"></el-input>
              </el-form-item>
              <el-form-item label="车牌号码：" prop="carNumber">
                <el-input placeholder="请输入车牌号码" v-model="carInfoForm.carNumber" style="width: 480px;"></el-input>
              </el-form-item>
              <el-form-item label="车辆品牌：" prop="carBrand">
                <el-input placeholder="请输入车辆品牌" v-model="carInfoForm.carBrand" style="width: 480px;"></el-input>
              </el-form-item>
            </el-form>
          </div>
        </div>
            <div class="card-main">
          <text>最近一次月卡缴费信息</text>
           <el-divider />
          <div>
            <el-form  ref="feeFormRef" :model="feeForm" :rules="feeFormRules" style="display: flex; flex-wrap: wrap;padding-right: 50px;
            margin-left: 130px; justify-content: space-between; 
            width: 90%;
            ">
              <el-form-item label="有效日期：" prop="cardEndDate">
               <div class="block">
              <el-date-picker
                v-model="cardDataArr"
                type="datetimerange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD HH:mm"
                date-format="YYYY/MM/DD ddd"
                time-format="A hh:mm:ss"
              />
            </div>
              </el-form-item>
              <el-form-item label="支付金额：" prop="paymentAmount">
                <el-input placeholder="请输入支付金额" v-model="feeForm.paymentAmount" style="width: 480px;"></el-input>
              </el-form-item>
                <el-form-item label="支付方式：" prop="paymentMethod">
                  <el-select v-model="feeForm.paymentMethod" placeholder="请选择支付方式" style="width: 240px">
                    <el-option  v-for="item in payMethodList" :key="item.id"  :value="item.id" :label="item.name" />
                  </el-select>
                </el-form-item>
      
            </el-form>
          </div>
        </div>
    </main>
    </div>
    <footer>
      <div class="footer">
        <el-button @click="onReset()">重置</el-button>
        <el-button type="primary" @click="onSubmit()">确定</el-button>
      </div>
    </footer>
  </div>
</template>

<script setup lang='ts'>
import { createCard, getParkingCardDetail, getParkingCardEdit } from '@/apis/card';
import router from '@/router';
import type { EditCardParams } from '@/types/card';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { ref, watch } from 'vue';
import { useRoute } from 'vue-router';


// 重置表单
const onReset = () =>{
  // 
    feeFormRef.value?.resetFields()
    carInfoFormRef.value?.resetFields()
    // 清空数组
    cardDataArr.value = []
}
// 点击确定提交表单
const onSubmit = async () =>{
  try{
    await Promise.all([
      carInfoFormRef.value?.validate(),
      feeFormRef.value?.validate()
    ])

    if(route.params.id){
      await  getParkingCardEdit(route.params.id as string,{
        ...carInfoForm.value,
        ...feeForm.value,
       ...editForm.value})
    }else{
  //  无id 是新增月卡
    await createCard({
      ...carInfoForm.value,
      ...feeForm.value
    })
    }
  
    ElMessage.success(route.params.id ? '编辑成功' :'添加成功')
    // 返回上一级
    router.back()
    
  }catch (error) {
    // 处理验证失败的逻辑（如显示错误信息）
    console.error('表单验证失败:', error);
  }
}

// 拿到两个表单
const carInfoFormRef = ref<FormInstance>()
const feeFormRef = ref<FormInstance>()

// 日期数组
const cardDataArr = ref<string[]>([])

// 车辆信息接口
interface CardParams {
  personName:string,
  phoneNumber :string,
  carNumber:string,
  carBrand:string,
  cardStartDate :string,
  cardEndDate :string,
  paymentAmount?:string,
  paymentMethod:string
}

// 最近一次月卡缴费

const feeForm = ref<Required<Pick<CardParams, 'cardStartDate' | 'cardEndDate' | 'paymentAmount' | 'paymentMethod'>>>({
  cardStartDate: '',
  cardEndDate: '',
  paymentAmount: '',
  paymentMethod: ''
})


// 监听日期变化 收集后端需要的数据
watch(cardDataArr, (val) =>{
  if(val){
    feeForm.value.cardStartDate = val[0]
    feeForm.value.cardEndDate = val[1]
   
  }else{
    feeForm.value.cardStartDate = ''
    feeForm.value.cardEndDate = ''
  }
})

const feeFormRules = ref<FormRules<CardParams>>({
  cardEndDate:[{required:true,message:'请选择有效日期',trigger:'blur'}],
  paymentAmount:[{required:true,message:'请输入支付金额',trigger:'blur'}],
  paymentMethod:[{required:true,message:'请选择支付方式',trigger:'change'}]
})


const carInfoRules = ref<FormRules<CardParams>>({
  personName:[{required:true,message:'请输入车主姓名',trigger:'blur'}],
  phoneNumber:[{required:true,message:'请输入联系方式',trigger:'blur'},
    {pattern:/^(?:(?:\+|00)86)?1\d{10}$/,message:'请输入正确的手机号',trigger:'blur'}
  ],
  carNumber:[{required:true,message:'请输入车牌号码',trigger:'blur'},
    {pattern:/^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$/,
      message:'请输入正确的车牌号',trigger:'blur'
    }
  ],
  carBrand:[{required:true,message:'请输入车辆品牌',trigger:'blur'}]
})
const carInfoForm = ref<Required<Pick<CardParams, 'personName' | 'phoneNumber' | 'carNumber' | 'carBrand'>>>({
  personName: '',
  phoneNumber: '',
  carNumber: '',
  carBrand: ''
})

// 支付方式列表
const payMethodList = [
  {id:'Alipay',name:'支付宝'},
  {id:'WeChat',name:'微信'},
  {id:'Cash',name:'线下'}
]

// 编辑时，保存月卡车辆id 和 缴费信息 id
const editForm = ref<Partial<EditCardParams>>({
  carInfoId:undefined,
  rechargeId:undefined
})

// 获取月卡详情
const getCardDetail = async () =>{
  //根据id获取
  const res = await getParkingCardDetail(route.params.id as string)
  console.log('获取月卡详情:',res)

  const {personName,phoneNumber,carNumber,carBrand,cardEndDate ,cardStartDate,
    paymentAmount,paymentMethod,carInfoId,rechargeId} = res.data
     // 提取车辆信息表单数据
     carInfoForm.value = { personName, phoneNumber, carNumber, carBrand }
  // 提取最近一次月卡缴费信息数据
    feeForm.value = {cardEndDate ,cardStartDate, paymentAmount,paymentMethod}
    // 单独处理日期数组
    cardDataArr.value = [cardStartDate,cardEndDate]
    // 绑定到表单3 编辑时 所需的两个id 看不到的表单
    editForm.value = {carInfoId,rechargeId}
}

// 获取路由参数
const route = useRoute()
// 如果有id 调用接口
if(route.params.id){
  getCardDetail()
}
</script>
<style lang='scss' scoped>


.footer{
  background-color: #fff;
  height: 64px;
  display: flex;
  justify-content: center;
  align-items: center;


}
.add-card {

   background-color: #f4f6f8;
  height: 100vh;
  display: flex;
  flex-direction:column;
  justify-content: space-between;

  .card-main{
     background:#fff;
    margin: 20px 130px;
    height: 200px ;
    padding: 20px;
  }
}
.header {
  background-color:#fff;
  height: 64px;
  display: flex;
  width: 100%;
  align-items: center;
  justify-content:space-between
}
.card-main {
  background: #f4f6f8;
  padding: 20px 130px;
}
</style>